import { MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { ChatService } from './chat.service';
import { Server, Socket } from 'socket.io';
import { Inject } from '@nestjs/common';
import { ChatHistoryService } from 'src/chat-history/chat-history.service';
import { UserService } from 'src/user/user.service';

interface JoinRoomPayload {
    chatroomId: number
    userId: number
}

interface SendMessagePayload {
    sendUserId: number;
    chatroomId: number;
    message: {
        type: 'text' | 'image',  // type 可以是 text、image
        content: string
    }
}

/* 
    开启跨域
    监听 joinRoom、sendMessage 消息
    - joinRoom 把 client socket 加入房间，房间号为直接用聊天室 id。
    - sendMessage 接收并广播消息到对应房间

*/
@WebSocketGateway({ cors: { origin: '*' } })
export class ChatGateway {
    @Inject(ChatHistoryService)
    private chatHistoryService:ChatHistoryService;

    @Inject(UserService)
    private userService: UserService

    constructor(private readonly chatService: ChatService) { }

    @WebSocketServer() server: Server;

    @SubscribeMessage('joinRoom')
    joinRoom(client: Socket, payload: JoinRoomPayload): void {
        const roomName = payload.chatroomId.toString();

        client.join(roomName)

        this.server.to(roomName).emit('message', {
            type: 'joinRoom',
            userId: payload.userId
        });
    }

    @SubscribeMessage('sendMessage')
    async sendMessage(@MessageBody() payload: SendMessagePayload) {
        const roomName = payload.chatroomId.toString();

        // 保存聊天记录到数据库
        const history = await this.chatHistoryService.add(payload.chatroomId ,{
            type:payload.message.type === 'image' ? 1 : 0,
            content: payload.message.content,
            chatroomId: payload.chatroomId,
            senderId: payload.sendUserId
        })
        // 每次请求时 收集 senderId 对应的 userInfo  这样不需要每次重新请求接口  websocket 完全可以应对
        const sender = await this.userService.getUserInfoByid(history.senderId)
        this.server.to(roomName).emit('message', {
            type: 'sendMessage',
            userId: payload.sendUserId,
            message: {
                ...history,
                sender
            }
        });
    }
}
